<template>
  <div class="hello">
    <div class="query">
      快速定位:
      <el-select v-model="query" filterable remote reserve-keyword placeholder="搜索地点名称" :remote-method="onSearch"
        :loading="loading" value-key="id" @change="onChange">
        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item">
        </el-option>
      </el-select>
      <div class="label-tips">请使用地图左上角<span class="circle-icon"></span>，在地图上标记出物联网设备的建设范围。如果范围标记错误，可以使用<i class="el-icon-edit-outline"></i>、<i class="el-icon-delete"></i>进行修改或删除。</div>
    </div>
    <div id="draw-map"></div>

    <div class="info">
      当前信息: <span v-if="currentLayer">经度: {{ currentLayer.lng }} 纬度: {{ currentLayer.lat }} 半径:
        {{ currentLayer.radius.toFixed(2) }}米</span><span v-else>请在地图上绘制</span>
    </div>
  </div>
</template>

<script>
import Map from '@/utils/map';
export default {
  name: 'Draw',
  props: {
    msg: String,
    id: String,
    initData: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      map: null,
      plottingLayer: null,
      drawControl: null,
      editableLayers: null,
      currentLayer: null,
      query: '',
      loading: false,
      options: [],
      marker: null
    }
  },
  mounted() {
    setTimeout(() => {
      Map.init({
        elId: 'draw-map',
        search: false,
        ready: (map) => {
          this.map = map
          this.initDraw()
        }
      })
      if (this.initData.latitude) {
        this.initCircle()
      }
    }, 500)
  },
  methods: {
    initDraw() {
      let map = this.map;
      var editableLayers = new L.FeatureGroup();
      map.addLayer(editableLayers);

      let drawControl = new L.Control.Draw({
        edit: {
          featureGroup: editableLayers,
          poly: {
            allowIntersection: false
          }
        },
        draw: {
          polygon: false,
          rectangle: false,
          circle: {
            radius: 10000
          },
          marker: false,
          polyline: false,
          circlemarker: false,
        },

      });
      map.addControl(drawControl);

      map.on(L.Draw.Event.CREATED, (e) => {
        var type = e.layerType,
          layer = e.layer;

        if (type === 'marker') {
          layer.bindPopup('A popup!');
        }
        layer.type = type
        if (editableLayers.getLayers().length > 0) return this.$message.warning('只允许绘制一个位置');
        editableLayers.addLayer(layer);
        this.$emit('change', this.getLayerData(layer))
      });
      map.on('draw:edited', (e) => {
        e.layers.eachLayer((layer) => {
          this.$emit('change', this.getLayerData(layer))
        })
      })
      this.drawControl = drawControl
      this.editableLayers = editableLayers
    },
    drawCircle() {
      let center = L.latLng([28, -75]);
      console.log(L.Draw)
      let circle = new L.Circle(center, 2000000, {})
      this.map.addLayer(circle)
      this.editableLayers.addLayer(circle)
    },
    editCircle() {
      this.drawControl.fire('edit')
    },
    getLayerData(layer) {
      if (layer.type === 'circle') {
        const result =  {
          ...layer.getLatLng(),
          radius: layer.getRadius()
        };
        this.currentLayer = result;
        return result;
      }
    },
    clearData() {
      console.log(this.editableLayers)
    },
    initCircle() {
      const { latitude, longitude, radius } = this.initData
      let center = L.latLng([latitude, longitude]);
      let circle = new L.Circle(center, radius, {})
      circle.type = 'circle';
      this.map.addLayer(circle)
      this.editableLayers.addLayer(circle)
      this.getLayerData(circle)
    },
    onSearch(value) {
      if (!value || this.loading) return;
      this.loading = true;
      Map.searchPOI(value).then(res => {
        console.log(res)
        this.loading = false;
        if (res.result && res.result.succeed) {
          const { features } = res.result.features
          this.options = features.map(item => {
            const [lng, lat] = item.geometry.coordinates;
            const name = item.properties.NAME;
            return {
              name,
              lng,
              lat,
              id: item.id
            }
          })
          console.log(this.options)
          // const [lng,lat]= features[0].geometry.coordinates;
          // this.map.setView(L.latLng(lat,lng), 8)
        }
      })
    },
    onChange(value) {
      const { lng, lat } = value;
      const point = L.latLng(lat, lng);
      this.map.setView(L.latLng(lat, lng), 6)
      if (!this.marker) {
        const marker = new L.Marker(point, {
          icon: Map.getIcon()
        })
        this.map.addLayer(marker)
        this.marker = marker;
      } else {
        this.marker.setLatLng(point)
      }
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
#draw-map {
  width: 100%;
  height: 600px;
}
.query{
  margin-bottom: 10px;
  display: flex;
}
.info{
  margin: 10px 0;
}
.label-tips{
  width: 62%;
  color: red;
  font-size: 12px;
  margin-left: 10px;
  i{
    color: #000000;

  }
  .circle-icon{
      display: inline-block;
      width: 8px;
      height: 8px;
      background-color: #000;
      border-radius: 50%;
      margin-left: 2px;
    }
}
</style>
